<template>
  <a-modal
    v-model:open="visible"
    centered
    :title="modalTitle"
    width="600px"
    :confirm-loading="confirmLoading"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <a-form ref="formRef" :model="formState" layout="vertical" name="teacherForm" autocomplete="off" :rules="rules">
      <a-form-item label="所属组织" name="orgIds">
        <a-tree-select
          v-model:value="formState.orgIds"
          :loading="organizationOptionsLoading"
          mode="multiple"
          tree-checkable
          tree-default-expand-all
          :tree-data="treeData"
          tree-check-strictly
          :field-names="{ children: 'children', label: 'orgName', value: 'id' }"
          placeholder="请选择任教范围"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import type { Rule } from 'ant-design-vue/es/form'
  import { TreeSelectProps } from 'ant-design-vue/es/tree-select'
  import { reactive, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import { useModalForm } from '@/hooks/use-modal-form'
  import { teacherManageApi } from '@/services/api/aigc-admin'

  export interface FormState {
    orgIds?: string[]
  }

  const emits = defineEmits<{
    (e: 'submit', state: FormState): void
    (e: 'close'): void
  }>()

  const rules: Record<string, Rule[]> = {
    orgIds: [{ required: true, message: '请选择组织', trigger: 'change' }]
  }

  const formState = reactive<FormState>({
    orgIds: undefined
  })

  const { formRef, visible, modalTitle, confirmLoading, open, close, setFormState, resetForm, changeConfirmLoading } =
    useModalForm(formState)

  const treeData = ref<TreeSelectProps['treeData']>([])
  const { loading: organizationOptionsLoading, refresh } = useRequest<any>(teacherManageApi.getOrganizationTree, {
    onSuccess({ data }) {
      treeData.value = data || []
    }
  })
  watch(
    () => visible.value,
    val => val && refresh()
  )

  const onClose = () => {
    close()
    emits('close')
  }

  const onSubmit = async () => {
    await formRef.value?.validate()
    emits('submit', formState)
  }

  defineExpose({
    open,
    close,
    setFormState,
    resetForm,
    changeConfirmLoading
  })
</script>
